package kata.chop;

public abstract class BinaryChop {

	protected static final int NOT_FOUND = -1;
	protected int[] searchIn;
	protected int lookFor;
	protected int startPosition;
	protected int endPosition;
	protected int middlePosition;

	/**
	 * Template method.
	 */
	public int chop(int lookFor, int[] searchIn) {
		init(lookFor, searchIn);
		if (isEmpty())
			return NOT_FOUND;
		else {
			return chop();
		}
	}

	protected abstract int chop();

	protected void init(int lookFor, int[] searchIn) {
		this.lookFor = lookFor;
		this.searchIn = searchIn;
		startPosition = 0;
		endPosition = searchIn.length - 1;
	}

	protected boolean found() {
		return searchIn[middlePosition] == lookFor;
	}

	protected boolean searchTheRightHalf() {
		return searchIn[middlePosition] < lookFor;
	}

	protected boolean searchTheLeftHalf() {
		return searchIn[middlePosition] > lookFor;
	}

	protected void computeMiddle() {
		middlePosition = ((endPosition - startPosition) / 2) + startPosition;
	}

	private boolean isEmpty() {
		return searchIn.length == 0;
	}

}